package com.gzx.qc.modular.inspection.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gzx.qc.modular.inspection.bo.GzxManualQualityInspectionAddBo;
import com.gzx.qc.modular.inspection.bo.GzxManualQualityInspectionQueryBo;
import com.gzx.qc.modular.inspection.constant.InspectionConstant;
import com.gzx.qc.modular.inspection.entity.GzxManualQualityInspection;
import com.gzx.qc.modular.inspection.mapper.GzxManualQualityInspectionMapper;
import com.gzx.qc.modular.inspection.service.GzxManualQualityInspectionService;
import com.gzx.qc.modular.inspection.vo.GzxInspectionStatusVo;
import com.gzx.qc.modular.inspection.vo.GzxManualQualityInspectionVo;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.mvc.service.impl.BaseServiceImpl;
import vip.xiaonuo.common.util.CommonCryptogramUtil;
import vip.xiaonuo.common.util.CommonExcelUtil;
import vip.xiaonuo.sys.api.SysUserApi;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author xbl
 */
@Slf4j
@Service
@DS("tjzy-async")
public class GzxManualQualityInspectionServiceImpl extends BaseServiceImpl<GzxManualQualityInspectionAddBo, GzxManualQualityInspectionVo, GzxManualQualityInspectionQueryBo, GzxManualQualityInspectionMapper, GzxManualQualityInspection> implements GzxManualQualityInspectionService {

    private final SysUserApi sysUserFeign;

    public GzxManualQualityInspectionServiceImpl(GzxManualQualityInspectionMapper baseMapper, SysUserApi sysUserFeign) {
        super(baseMapper);
        this.sysUserFeign = sysUserFeign;
    }

    @Override
    public void insert(GzxManualQualityInspectionAddBo bo) {
        //跟话单id获取手机号,前台传过来的手机号是带星号的,没有deptId
        GzxManualQualityInspectionVo vo = getReceiptById(bo.getId());
        if (!ObjectUtils.isEmpty(vo)) {
            bo.setCallee(vo.getCallee());
            bo.setDeptId(vo.getDeptId());
            bo.setCallType(vo.getCallType());
            bo.setFileUrl(vo.getFileUrl());
        } else {
            log.info("gzx_ht_call_receipt_business表话单id 不存在 : {}", bo);
        }

        GzxManualQualityInspection inspection = new GzxManualQualityInspection();
        //属性拷贝排除id
        BeanUtils.copyProperties(bo, inspection, "id");

        baseMapper.insert(inspection);
    }

    //根据id获取话单
    private GzxManualQualityInspectionVo getReceiptById(Long id) {
        return baseMapper.getReceiptById(id);
    }

    @Override
    public Page<GzxManualQualityInspectionVo> pageList(GzxManualQualityInspectionQueryBo queryBo) {
        Page<GzxManualQualityInspectionVo> list = baseMapper.selectVoPage(new Page<>(queryBo.getCurrent(), queryBo.getSize()), buildQueryWrapper(queryBo));
        //把list中的callee解密成手机号
        list.getRecords().forEach(vo -> {
            //只脱敏加密的手机号
            if (!ObjectUtils.isEmpty(vo.getCallee()) && vo.getCallee().length() > 11) {
                vo.setCallee(CommonCryptogramUtil.doSm1AesDecrypt(vo.getCallee()));
            }
        });
        return list;
    }

    /**
     * 人工质检分页
     */
    @Override
    protected LambdaQueryWrapper<GzxManualQualityInspection> buildQueryWrapper(GzxManualQualityInspectionQueryBo queryBo) {
        log.info("人工质检分页-查询参数：{} ", queryBo);
        return Wrappers.<GzxManualQualityInspection>lambdaQuery()
                .eq(!ObjectUtils.isEmpty(queryBo.getCallId()), GzxManualQualityInspection::getCallId, queryBo.getCallId())
                .eq(!ObjectUtils.isEmpty(queryBo.getCallee()), GzxManualQualityInspection::getCallee, CommonCryptogramUtil.doSm1AesEncrypt(queryBo.getCallee()))
                .eq(!ObjectUtils.isEmpty(queryBo.getCaller()), GzxManualQualityInspection::getCaller, queryBo.getCaller())
                .eq(!ObjectUtils.isEmpty(queryBo.getQcInspector()), GzxManualQualityInspection::getQcInspector, queryBo.getQcInspector())
                .eq(!ObjectUtils.isEmpty(queryBo.getAgentNum()), GzxManualQualityInspection::getAgentNum, queryBo.getAgentNum())
                .eq(!ObjectUtils.isEmpty(queryBo.getUserName()), GzxManualQualityInspection::getUserName, queryBo.getUserName())
                .eq(!ObjectUtils.isEmpty(queryBo.getDeptId()), GzxManualQualityInspection::getDeptId, queryBo.getDeptId())
                .eq(!ObjectUtils.isEmpty(queryBo.getInspection()), GzxManualQualityInspection::getInspection, queryBo.getInspection())
                .eq(!ObjectUtils.isEmpty(queryBo.getRemark()), GzxManualQualityInspection::getRemark, queryBo.getRemark())
                .between(!ObjectUtils.isEmpty(queryBo.getBeginTime()) && !ObjectUtils.isEmpty(queryBo.getEndTime()), GzxManualQualityInspection::getCreateTime, queryBo.getBeginTime(), queryBo.getEndTime())
                .orderByDesc(GzxManualQualityInspection::getId);
    }

    /**
     * 人工质检导出
     */
    @Override
    public void exportInspectionReport(GzxManualQualityInspectionQueryBo queryBo, HttpServletResponse response) {
        if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isEmpty(queryBo.getBeginTime()) || com.baomidou.mybatisplus.core.toolkit.StringUtils.isEmpty(queryBo.getEndTime())) {
            throw new CommonException("时间不允许为空");
        }
        //只导出查询的数据
        List<GzxManualQualityInspectionVo> inspectionVo = baseMapper.selectVoList(Wrappers.<GzxManualQualityInspection>lambdaQuery()
                .eq(!ObjectUtils.isEmpty(queryBo.getCallId()), GzxManualQualityInspection::getCallId, queryBo.getCallId())
                .eq(!ObjectUtils.isEmpty(queryBo.getCallee()), GzxManualQualityInspection::getCallee, CommonCryptogramUtil.doSm1AesEncrypt(queryBo.getCallee()))
                .eq(!ObjectUtils.isEmpty(queryBo.getQcInspector()), GzxManualQualityInspection::getQcInspector, queryBo.getQcInspector())
                .eq(!ObjectUtils.isEmpty(queryBo.getCaller()), GzxManualQualityInspection::getCaller, queryBo.getCaller())
                .eq(!ObjectUtils.isEmpty(queryBo.getAgentNum()), GzxManualQualityInspection::getAgentNum, queryBo.getAgentNum())
                .eq(!ObjectUtils.isEmpty(queryBo.getUserName()), GzxManualQualityInspection::getUserName, queryBo.getUserName())
                .eq(!ObjectUtils.isEmpty(queryBo.getDeptId()), GzxManualQualityInspection::getDeptId, queryBo.getDeptId())
                .eq(!ObjectUtils.isEmpty(queryBo.getInspection()), GzxManualQualityInspection::getInspection, queryBo.getInspection())
                .eq(!ObjectUtils.isEmpty(queryBo.getRemark()), GzxManualQualityInspection::getRemark, queryBo.getRemark())
                .between(!ObjectUtils.isEmpty(queryBo.getBeginTime()) && !ObjectUtils.isEmpty(queryBo.getEndTime()), GzxManualQualityInspection::getCreateTime, queryBo.getBeginTime(), queryBo.getEndTime())
                .orderByDesc(GzxManualQualityInspection::getId));
        if (CollUtil.isNotEmpty(inspectionVo)) {
            //封装数据到excel中
            setInspectionReport(inspectionVo);
            //导出
            CommonExcelUtil.exportExcel("人工质检", inspectionVo, GzxManualQualityInspectionVo.class, response);
        } else {
            throw new CommonException("无可导出的数据");
        }
    }

    /**
     * 批量获取质检消息
     */
    @Override
    public List<GzxInspectionStatusVo> getStatusList(List<String> callIds) {
        return baseMapper.getStatusList(callIds);
    }

    /**
     * 获取质检状态
     */
    @Override
    public GzxInspectionStatusVo getStatus(String callId) {
        GzxInspectionStatusVo vo = new GzxInspectionStatusVo();
        //根据callId查询数据
        GzxManualQualityInspectionVo one = baseMapper.selectVoOne(Wrappers.<GzxManualQualityInspection>lambdaQuery().eq(GzxManualQualityInspection::getCallId, callId).last("limit 1"));
        if (!ObjectUtils.isEmpty(one)) {
            //属性拷贝
            BeanUtils.copyProperties(one, vo);
            //根据质检员账号查询用户名
            Set<String> accountSet = new HashSet<>();
            accountSet.add(vo.getQcInspector());
            List<JSONObject> user = sysUserFeign.getUserByAccount(accountSet);
            if (!ObjectUtils.isEmpty(user)) {
                vo.setQcInspectorName(user.getFirst().getStr("name"));
            }
        }
        return vo;
    }

    /**
     * 封装数据到excel中
     */
    private void setInspectionReport(List<GzxManualQualityInspectionVo> inspectionVo) {
        //导出的数据不能自动翻译
        Set<String> accountSet = inspectionVo.stream().map(GzxManualQualityInspectionVo::getAgentNum).collect(Collectors.toSet());
        List<cn.hutool.json.JSONObject> userList = sysUserFeign.getUserByAccount(accountSet);
        Map<String, JSONObject> userMap = new HashMap<>();
        for (cn.hutool.json.JSONObject str : userList) {
            userMap.put(str.getStr("account"), str);
        }
        //质检员
        Set<String> inspectorSet = inspectionVo.stream().map(GzxManualQualityInspectionVo::getQcInspector).collect(Collectors.toSet());
        List<cn.hutool.json.JSONObject> inspectorList = sysUserFeign.getUserByAccount(inspectorSet);
        Map<String, JSONObject> inspectorMap = new HashMap<>();
        for (cn.hutool.json.JSONObject str : inspectorList) {
            inspectorMap.put(str.getStr("account"), str);
        }
        for (GzxManualQualityInspectionVo vo : inspectionVo) {
            //导出的手机号要解密
            vo.setCallee(CommonCryptogramUtil.doSm1AesDecrypt(vo.getCallee()));
            //质检结果
            if (!ObjectUtils.isEmpty(vo.getInspection())) {
                InspectionConstant result = InspectionConstant.fromCode(Integer.parseInt(vo.getInspection()));
                vo.setInspection(result.getDescription());
            }
            //坐席
            cn.hutool.json.JSONObject jsonObject = userMap.get(vo.getAgentNum());
            if (!ObjectUtils.isEmpty(jsonObject)) {
                vo.setUserName(jsonObject.getStr("name"));
                //导出的部门名称没有自动翻译出来，使用坐席的部门名称
                vo.setCompanyName(jsonObject.getStr("orgName"));
            }
            //质检员
            cn.hutool.json.JSONObject inspectorObject = inspectorMap.get(vo.getQcInspector());
            if (!ObjectUtils.isEmpty(inspectorObject)) {
                vo.setQcInspector(inspectorObject.getStr("name"));
            }
        }
    }
}
